package com.googlecode.placesapiclient.client;

import com.googlecode.placesapiclient.client.exception.ErrorCode;
import com.googlecode.placesapiclient.client.exception.ErrorCodeException;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 *
 */
public class StatusCodeAnalyzer {

    public static void analyzeResponse(JSONObject jsonObject) throws ErrorCodeException {

        validateResponse(jsonObject);

        try {
            String status = jsonObject.getString("status");
            StatusCode statusCode = StatusCode.valueOf(status);
            if(statusCode.getErrorCode() != ErrorCode.OK) {
                throw new ErrorCodeException(statusCode.getErrorCode(), "Returned status: " + status);
            }
        } catch (JSONException e) {
            throw new ErrorCodeException(ErrorCode.MISSING_STATUS, "Invalid JSONObject element: no status returned");
        } catch (IllegalArgumentException e){
            throw new ErrorCodeException(ErrorCode.INVALID_PARAMETER, "Invalid JSONObject element: returned status is not supported");
        }

    }

    private static void validateResponse(JSONObject jsonObject) throws ErrorCodeException {
        if(jsonObject==null) {
            throw new ErrorCodeException(ErrorCode.INVALID_PARAMETER, "Invalid JSONObject: null passed");
        }

        if(!jsonObject.has("status")) {
            throw new ErrorCodeException(ErrorCode.MISSING_STATUS, "Invalid JSONObject element: no status returned");
        }
    }
}
